/*
 * ExitAction.java
 *
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.actions.system;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import org.tiberiumlabs.lailaps.actions.AbstractResourcedAction;
import org.tiberiumlabs.lailaps.actions.ActionFactory;
import org.tiberiumlabs.lailaps.gui.GUIBuilder;
import org.tiberiumlabs.lailaps.gui.GUIFactory;
import org.tiberiumlabs.lailaps.gui.droptarget.DropTarget;
import org.tiberiumlabs.lailaps.gui.elements.TableColumnModel;
import org.tiberiumlabs.lailaps.list.ListStorage;
import org.tiberiumlabs.lailaps.resources.ImageLoader;
import org.tiberiumlabs.lailaps.settings.InterfaceSettingsImpl;
import org.tiberiumlabs.lailaps.settings.Settings;
import org.tiberiumlabs.lailaps.tray.TrayFactory;
import org.tiberiumlabs.swing.DesktopToolkit;

/**
 *
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class ExitAction extends AbstractResourcedAction implements WindowListener {

    private JWindow window = null;

    /** Creates a new instance of ExitAction */
    public ExitAction() {
        putValue(NAME, bundle.getString("exit.name"));
        putValue(SHORT_DESCRIPTION, bundle.getString("exit.short"));
        putValue(LONG_DESCRIPTION, bundle.getString("exit.long"));
        putValue(SMALL_ICON, ImageLoader.getMenuExitIcon());
    }

    private void performAction() {

        if (Settings.getApplicationSettings().isAskBeforeExit()) {
            // if we need to ask and user dont choose OK - return out of here.
            GUIBuilder guiBuilder = mediator.getGuiBuilder();
            if (JOptionPane.showConfirmDialog(guiBuilder.isMainWindowVisible() ? guiBuilder.getMainWindow() : null, "are you sure you want to exit programm?", "Really exit?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
                return;
            }
        }

        if (SwingUtilities.isEventDispatchThread()) {
            showProgress();
            Thread thread = new Thread("Lailaps Shutdown") {

                @Override
                public void run() {
                    shutdown();
                }
            };
            thread.start();
        } else {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    showProgress();
                }
            });
            shutdown();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        performAction();
    }

    @Override
    public void windowClosing(WindowEvent e) {
        performAction();
    }

    private void showProgress() {

        JProgressBar progress = new JProgressBar(JProgressBar.HORIZONTAL);
        progress.setBorderPainted(true);
        progress.setIndeterminate(true);
        progress.setStringPainted(true);
        progress.setString(bundle.getString("exit.progress"));
        progress.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));

        JPanel contentPane = GUIFactory.createVerticalBoxPanel();
        contentPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(70, 80, 90)), BorderFactory.createEmptyBorder(12, 12, 12, 12)));
        contentPane.add(progress);

        window = new JWindow();
        window.setContentPane(contentPane);
        window.pack();
        if (window.getWidth() < 400) {
            window.setSize(400, window.getHeight());
        }
        window.setLocation(DesktopToolkit.getWindowLocation(window.getSize()));
        window.setVisible(true);
    }

    private void shutdown() {

        try {
            // save size and position of window
            InterfaceSettingsImpl settingsWriter = Settings.getEditableInterfaceSettings();
            GUIBuilder guiBuilder = mediator.getGuiBuilder();
            if (guiBuilder.isMainWindowVisible()) {

                // saving columns orders and sizes
                settingsWriter.setTableColumnOrder(((TableColumnModel)guiBuilder.getTable().getColumnModel()).getColumnsOrder());

                JFrame mainWindow = guiBuilder.getMainWindow();
                settingsWriter.setMainWindowX(mainWindow.getX());
                settingsWriter.setMainWindowY(mainWindow.getY());
                settingsWriter.setMainWindowWidth(mainWindow.getWidth());
                settingsWriter.setMainWindowHeight(mainWindow.getHeight());
                mainWindow.dispose();
            }
            if (guiBuilder.isDropTargetVisible()) {
                DropTarget dropTarget = guiBuilder.getDropTarget();
                settingsWriter.setDroptargetWindowX(dropTarget.getX());
                settingsWriter.setDroptargetWindowY(dropTarget.getY());
                settingsWriter.setDroptargetWindowHeight(dropTarget.getHeight());
                settingsWriter.setDroptargetWindowWidth(dropTarget.getWidth());
                dropTarget.dispose();
            }
            Settings.saveInterfaceSettings();

            // closing tray icon:
            TrayFactory.closeTrayIcon();

            // TODO think we don't need it anymore if we have finally block:
            // save list before try to shutdown - to make sure it will be saved
            //ListSaver.saveList();

            // TODO need stable system to stop concurently all threads and than save list
            // stopping background threads after actions not to do more work
            mediator.getThreadsMap().shutdown();

            // need to shutdown connection manager
            mediator.shutdownHttpClient();

            // stopping actions to stop all work
            ActionFactory.shutdown();

            // after threads stopped - save the list
            ListStorage storage = new ListStorage();
            storage.storeList();

        } catch (Exception ex) {

            System.out.println("Exception on shutdown: " + ex.getClass() + " " + ex.getMessage());
            ex.printStackTrace(System.out);

        } finally {

            // disposing window after everything is done
            if (window != null) {
                window.dispose();
                window = null;
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc=" just empty methods to implement WindowListener ">
    @Override
    public void windowClosed(WindowEvent e) {
        //performAction();
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

    // </editor-fold>
}
